﻿package fpc.utils;

class Herald< T >
{	
	public function new()
	{
		
	}
	
	var _listeners:Array<T->Dynamic>;
	
	public function add(listener:T->Dynamic)
	{
		if (_listeners == null)
		{
			_listeners = [listener];
		}
		else
		{
			_listeners.remove(listener);
			_listeners.push(listener);
		}
	}
	
	public function remove(listener:T->Dynamic)
	{
		if (_listeners != null)
		{
			return _listeners.remove(listener);
		}
		return false;
	}
	
	var _simples:Array<Void->Dynamic>;
	
	public function addSimple(listener:Void->Dynamic)
	{
		if (_simples == null)
		{
			_simples = [listener];
		}
		else
		{
			_simples.remove(listener);
			_simples.push(listener);
		}
	}
	
	public function removeSimple(listener:Void->Dynamic)
	{
		if (_simples != null)
		{
			return _simples.remove(listener);
		}
		return false;
	}
	
	public function dispatch(value:T)
	{
		if (disabled)
		{
			return;
		}
		if (_listeners != null)
		{
			for (listener in _listeners)
			{
				listener(value);
			}
		}
		if (_simples != null)
		{
			for (listener in _simples)
			{
				listener();
			}
		}
	}
	
	public var hasListeners(getHasListeners, null):Bool;
	function getHasListeners()
	{
		return _listeners != null && _listeners.length > 0 || _simples != null && _simples.length > 0;
	}
	
	public function removeAll()
	{
		_listeners = null;
		_simples = null;
	}
	
	public var disabled(default, null):Bool;
	
	var _index:Int;
	
	public function disableOn()
	{
		_index++;
		disabled = true;
	}
	
	public function disableOff()
	{
		if (--_index <= 0)
		{
			_index = 0;
			disabled = false;
		}
	}
}